package com.whcoding.test.common;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelUtil;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: spring-boot-learning
 * @description:
 * @author: whcoding
 * @create: 2022-04-18 16:03
 **/
public class HutoolPageUtil extends cn.hutool.core.util.PageUtil{

	private static final Logger log = LoggerFactory.getLogger(HutoolPageUtil.class);

	public static final String SYS_TEM_DIR = System.getProperty("java.io.tmpdir") + File.separator;

	/**
	 * List 分页
	 */
	public static List toPage(int page, int size , List list) {
		int fromIndex = page * size;
		int toIndex = page * size + size;
		if(fromIndex > list.size()){
			return new ArrayList();
		} else if(toIndex >= list.size()) {
			return list.subList(fromIndex,list.size());
		} else {
			return list.subList(fromIndex,toIndex);
		}
	}

	/**
	 * Page 数据处理，预防redis反序列化报错
	 */
	public static Map<String,Object> toPage(Page page) {
		Map<String,Object> map = new LinkedHashMap<>(2);
		map.put("content",page.getContent());
		map.put("totalElements",page.getTotalElements());
		return map;
	}

	/**
	 * 自定义分页
	 */
	public static Map<String,Object> toPage(Object object, Object totalElements) {
		Map<String,Object> map = new LinkedHashMap<>(2);
		map.put("content",object);
		map.put("totalElements",totalElements);
		return map;
	}

	/**
	 *  导出
	 * @param list
	 * @param response
	 * @throws IOException
	 */
	public static void downloadExcel(List<Map<String, Object>> list, HttpServletResponse response) throws IOException {
		String tempPath = SYS_TEM_DIR + IdUtil.fastSimpleUUID() + ".xlsx";
		File file = new File(tempPath);
		BigExcelWriter writer = ExcelUtil.getBigWriter(file);
		// 一次性写出内容，使用默认样式，强制输出标题
		writer.write(list, true);
		SXSSFSheet sheet = (SXSSFSheet)writer.getSheet();
		//上面需要强转 SXSSFSheet  不然没有trackAllColumnsForAutoSizing方法
//		sheet.trackAllColumnsForAutoSizing();
		//列宽自适应
		sheet.trackAllColumnsForAutoSizing();
		writer.autoSizeColumnAll();
		//response为HttpServletResponse对象
		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
		//test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
		response.setHeader("Content-Disposition", "attachment;filename=file.xlsx");
		ServletOutputStream out = response.getOutputStream();
		// 终止后删除临时文件
		file.deleteOnExit();
		writer.flush(out, true);
		//此处记得关闭输出Servlet流
		IoUtil.close(out);
	}


	/**
	 * 下载文件
	 *
	 * @param request  /
	 * @param response /
	 * @param file     /
	 */
	public static void downloadFile(HttpServletRequest request, HttpServletResponse response, File file, boolean deleteOnExit) {
		response.setCharacterEncoding(request.getCharacterEncoding());
		response.setContentType("application/octet-stream");
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
			IOUtils.copy(fis, response.getOutputStream());
			response.flushBuffer();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		} finally {
			if (fis != null) {
				try {
					fis.close();
					if (deleteOnExit) {
						file.deleteOnExit();
					}
				} catch (IOException e) {
					log.error(e.getMessage(), e);
				}
			}
		}
	}

}
